package com.mhc.haval.service.impl;

import com.mhc.haval.bo.DepartmentBO;
import com.mhc.haval.bo.DepartmentInfoBO;
import com.mhc.haval.constant.AreaEnum;
import com.mhc.haval.constant.IsDeletedEnum;
import com.mhc.haval.constant.MsgCodeEnum;
import com.mhc.haval.constant.StaffStatusEnum;
import com.mhc.haval.dal.mapper.ext.DepartmentExtMapper;
import com.mhc.haval.dal.model.DepartmentDO;
import com.mhc.haval.dal.model.DeptBizAreaDO;
import com.mhc.haval.dal.model.StaffDO;
import com.mhc.haval.dal.query.DepartmentQuery;
import com.mhc.haval.dal.query.DeptBizAreaQuery;
import com.mhc.haval.dal.query.StaffQuery;
import com.mhc.haval.exception.HavalCommonException;
import com.mhc.haval.manager.DepartmentManager;
import com.mhc.haval.manager.DeptBizAreaManager;
import com.mhc.haval.manager.StaffManager;
import com.mhc.haval.security.util.SessionUtil;
import com.mhc.haval.service.DepartmentService;
import com.mhc.haval.vo.DepartmentInfoVO;
import com.subaru.common.entity.BizResult;
import com.subaru.common.util.BeanCopierUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 增删改查部门信息
 * Created by HMJ on 2017/8/19.
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentManager departmentManager;

    @Autowired
    private DepartmentExtMapper departmentExtMapper;

    @Autowired
    private DeptBizAreaManager deptBizAreaManager;

    @Autowired
    private StaffManager staffManager;

    /**
     * 新增部门信息
     *
     * @param departmentBO 部门信息实体
     * @return
     */
    @Override
    public Boolean addDeptInfo(DepartmentBO departmentBO) throws HavalCommonException {
        log.info("校验部门名称是否相同...");
        DepartmentQuery departmentQuery = new DepartmentQuery();
        departmentQuery.createCriteria().andDeptNameEqualTo(departmentBO.getDeptName());
        List<DepartmentDO> departmentList = departmentManager.selectByQuery(departmentQuery);
        if (departmentList.isEmpty()) {
            log.info("校验成功，可以新增...");
            log.info("开始新增部门信息...");
            DepartmentDO departmentDO = new DepartmentDO();
            BeanCopierUtil.copy(departmentBO, departmentDO);
            if (departmentManager.insertSelective(departmentDO) != 1) {
                throw new HavalCommonException(MsgCodeEnum.INSERT_FAIL);
            }
            // 如果有业务地区范围那么添加
            if (null != departmentBO.getAreaId() && departmentBO.getAreaId() > 0) {
                this.addDeptBizArea(departmentBO, departmentDO.getDeptId());
                log.info("部门信息新增完成...");
            }
            return true;
        }
        return false;
    }

    /**
     * 逻辑删除部门
     *
     * @param deptId
     */
    @Override
    public BizResult delDept(Long deptId) {
        if (null == deptId || deptId < 0) {
            return BizResult.create(MsgCodeEnum.PARAM_ERROR.getErrCode(), MsgCodeEnum.PARAM_ERROR
                    .getErrMsg());
        }
        // 检查部门下是否存在员工或者下级部门，如果存在不允许删除部门
        List<DepartmentInfoVO> subDeptList = selectByDeptList(deptId, SessionUtil.getUserInfo()
                .getCompanyNo());
        if (CollectionUtils.isNotEmpty(subDeptList)) {
            return BizResult.create(MsgCodeEnum.CHILD_DEPT_EXISTS.getErrCode(), MsgCodeEnum.CHILD_DEPT_EXISTS
                    .getErrMsg());
        }
        StaffQuery query = new StaffQuery();
        query.createCriteria().andDeptIdEqualTo(deptId).andStatusEqualTo(StaffStatusEnum.NORMAL.getCode());
        List<StaffDO> subStaffList = staffManager.selectByQuery(query);
        if (CollectionUtils.isNotEmpty(subStaffList)) {
            return BizResult.create(MsgCodeEnum.DEPT_HAS_STAFFS.getErrCode(), MsgCodeEnum.DEPT_HAS_STAFFS
                    .getErrMsg());
        }

        // 删除部门与业务地区的记录
        DeptBizAreaDO deptBizAreaDO = new DeptBizAreaDO();
        deptBizAreaDO.setIsDeleted(IsDeletedEnum.DELETED.getCode());
        DeptBizAreaQuery deptBizAreaQuery = new DeptBizAreaQuery();
        deptBizAreaQuery.createCriteria().andDeptIdEqualTo(deptId);
        deptBizAreaManager.updateByQuerySelective(deptBizAreaDO, deptBizAreaQuery);

        // 逻辑删除部门
        DepartmentDO updateDo = new DepartmentDO();
        updateDo.setDeptId(deptId);
        updateDo.setIsDeleted(IsDeletedEnum.DELETED.getCode());
        departmentManager.updateByPrimaryKeySelective(updateDo);
        BizResult bizResult = BizResult.create();
        bizResult.setSuccess(true);
        return bizResult;
    }

    /**
     * 修改部门信息
     *
     * @param departmentBO 部门信息实体
     * @return
     */
    @Override
    public Boolean editDeptInfo(DepartmentBO departmentBO) throws HavalCommonException {
        log.info("开始修改部门信息...");
        DepartmentDO departmentDO = new DepartmentDO();
        DeptBizAreaDO deptBizAreaDO = new DeptBizAreaDO();
        deptBizAreaDO.setAreaId(departmentBO.getAreaId());      //省份ID
        deptBizAreaDO.setAreaName(departmentBO.getAreaName());  //省份名称
        if (departmentBO.getDeptId() == null) {
            throw new HavalCommonException(MsgCodeEnum.UPDATE_FAIL);
        }
        BeanCopierUtil.copy(departmentBO, departmentDO);
        if (departmentManager.updateByPrimaryKeySelective(departmentDO) != 1) {
            throw new HavalCommonException(MsgCodeEnum.UPDATE_FAIL);
        }
        log.info("部门信息修改完成...");
        if (departmentBO.getDeptBizAreaId() != null) {
            log.info("开始更新部门省份信息...");
            deptBizAreaDO.setDeptBizAreaId(departmentBO.getDeptBizAreaId());
            deptBizAreaManager.updateByPrimaryKeySelective(deptBizAreaDO);
            log.info("更新完成...");
        } else {
            log.info("开始新增部门省份信息...");
            deptBizAreaDO.setDeptId(departmentBO.getDeptId());             //部门id
            deptBizAreaDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());    //未删除
            deptBizAreaDO.setAreaType(AreaEnum.PROVINCE.getCode());    //省份
            deptBizAreaManager.insertSelective(deptBizAreaDO);
            log.info("新增完成...");
        }
        return true;
    }

    /**
     * 查询部门列表
     *
     * @param parentDeptId 上级部门ID
     * @param companyNo    公司ID
     * @return
     * @throws Exception
     */
    @Override
    public List<DepartmentInfoVO> selectByDeptList(Long parentDeptId, String companyNo) throws HavalCommonException {
        log.info("开始查询部门列表...");
        Map<String, Object> paramMap = new HashMap<>(64);
        paramMap.put("parentDeptId", parentDeptId);
        paramMap.put("companyNo", companyNo);
        paramMap.put("isDeleted", IsDeletedEnum.NORMAL.getCode());
        /**根据公司ID和上级部门ID查询部门列表**/
        List<DepartmentInfoBO> departmentInfoBOList = departmentExtMapper.queryByDeptList(paramMap);
        List<DepartmentInfoVO> departmentInfoVOList = new ArrayList<>();
        for (DepartmentInfoBO departmentInfoBO : departmentInfoBOList) {
            DepartmentInfoVO departmentInfoVO = new DepartmentInfoVO();
            BeanCopierUtil.copy(departmentInfoBO, departmentInfoVO);
            departmentInfoVOList.add(departmentInfoVO);
        }
        return departmentInfoVOList;
    }

    /**
     * 查看部门详情信息
     *
     * @param deptId 部门ID
     * @return
     */
    @Override
    public DepartmentInfoVO queryByInfo(Long deptId) throws HavalCommonException {
        if (deptId != null) {
            DepartmentInfoVO departmentInfoVO = new DepartmentInfoVO();
            DepartmentInfoBO departmentInfo = departmentExtMapper.queryByDeptInfo(deptId);
            BeanCopierUtil.copy(departmentInfo, departmentInfoVO);
            return departmentInfoVO;
        }
        throw new HavalCommonException(MsgCodeEnum.QUERY_FAIL);
    }

    /**
     * 新增部门区域信息
     *
     * @param departmentBO
     * @return
     * @throws HavalCommonException
     */
    public Boolean addDeptBizArea(DepartmentBO departmentBO, Long deptId) throws HavalCommonException {
        if (departmentBO.getAreaId() == null) {
            throw new HavalCommonException(MsgCodeEnum.PARAM_ERROR);
        }
        log.info("开始新增部门区域信息...");
        DeptBizAreaDO deptBizAreaDO = new DeptBizAreaDO();
        deptBizAreaDO.setDeptId(deptId);           //部门id
        deptBizAreaDO.setAreaId(departmentBO.getAreaId());       //省份id
        deptBizAreaDO.setAreaName(departmentBO.getAreaName());   //省份名称
        deptBizAreaDO.setAreaType(AreaEnum.PROVINCE.getCode());      //省份
        deptBizAreaDO.setIsDeleted(IsDeletedEnum.NORMAL.getCode());  //正常
        if (deptBizAreaManager.insertSelective(deptBizAreaDO) != 1) {
            throw new HavalCommonException(MsgCodeEnum.INSERT_FAIL);
        }
        log.info("新增部门区域信息完成...");
        return true;
    }

}
